<template>
  <div class="global-reminder-system">
    <!-- 提醒图标和计数器 -->
    <div 
      class="reminder-trigger" 
      :class="{ 'has-urgent': urgentReminders.length > 0 }"
      @click="toggleReminderPanel"
      v-if="reminderCount > 0"
    >
      <div class="reminder-icon">
        <i class="fas fa-bell"></i>
        <div class="reminder-badge" v-if="unreadCount > 0">
          {{ unreadCount > 99 ? '99+' : unreadCount }}
        </div>
      </div>
    </div>

    <!-- 提醒面板 -->
    <transition name="slide-left">
      <div class="reminder-panel" v-if="isReminderVisible">
        <!-- 面板头部 -->
        <div class="panel-header">
          <div class="header-title">
            <i class="fas fa-bell mr-2"></i>
            系统提醒
            <span class="count-badge">{{ reminderCount }}</span>
          </div>
          <div class="header-actions">
            <el-button 
              type="text" 
              size="small" 
              @click="markAllAsRead"
              v-if="unreadCount > 0"
            >
              全部已读
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="hideReminderPanel"
            >
              <i class="fas fa-times"></i>
            </el-button>
          </div>
        </div>

        <!-- 提醒筛选 -->
        <div class="panel-filters">
          <el-tabs v-model="activeTab" class="reminder-tabs">
            <el-tab-pane label="全部" name="all">
              <template #label>
                全部 <span class="tab-count">{{ activeReminders.length }}</span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="材料提醒" name="material">
              <template #label>
                材料 <span class="tab-count">{{ materialReminders.length }}</span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="紧急" name="urgent">
              <template #label>
                紧急 <span class="tab-count">{{ urgentReminders.length }}</span>
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 提醒列表 -->
        <div class="panel-content">
          <div class="reminder-list" v-if="filteredReminders.length > 0">
            <div 
              v-for="reminder in filteredReminders" 
              :key="reminder.id" 
              class="reminder-item"
              :class="{
                'unread': !reminder.read,
                'urgent': reminder.priority === 'urgent',
                'high': reminder.priority === 'high'
              }"
              @click="handleReminderClick(reminder)"
            >
              <!-- 提醒图标 -->
              <div class="reminder-item-icon">
                <i :class="getReminderIcon(reminder.type)"></i>
              </div>

              <!-- 提醒内容 -->
              <div class="reminder-item-content">
                <div class="reminder-item-header">
                  <h4 class="reminder-title">{{ reminder.title }}</h4>
                  <div class="reminder-meta">
                    <el-tag 
                      :type="getPriorityType(reminder.priority)" 
                      size="small"
                      class="priority-tag"
                    >
                      {{ getPriorityText(reminder.priority) }}
                    </el-tag>
                    <span class="reminder-time">{{ formatTime(reminder.createdAt) }}</span>
                  </div>
                </div>
                
                <p class="reminder-message">{{ reminder.message }}</p>
                
                <!-- 案件信息 -->
                <div class="reminder-case-info" v-if="reminder.caseNumber">
                  <span class="case-number">{{ reminder.caseNumber }}</span>
                  <span class="client-name" v-if="reminder.clientName">{{ reminder.clientName }}</span>
                </div>

                <!-- 截止时间 -->
                <div class="reminder-due-date" v-if="reminder.dueDate">
                  <i class="fas fa-clock mr-1"></i>
                  截止时间: {{ formatDate(reminder.dueDate) }}
                  <span 
                    class="overdue-warning" 
                    v-if="isOverdue(reminder.dueDate)"
                  >
                    (已逾期)
                  </span>
                </div>

                <!-- 操作按钮 -->
                <div class="reminder-actions" v-if="reminder.actions && reminder.actions.length > 0">
                  <el-button 
                    v-for="action in reminder.actions" 
                    :key="action.type"
                    type="primary" 
                    size="small" 
                    @click.stop="handleAction(reminder, action)"
                  >
                    <i :class="getActionIcon(action.type)" class="mr-1"></i>
                    {{ action.label }}
                  </el-button>
                </div>
              </div>

              <!-- 操作菜单 -->
              <div class="reminder-item-menu">
                <el-dropdown @command="handleMenuAction" trigger="click">
                  <el-button type="text" size="small" class="menu-trigger">
                    <i class="fas fa-ellipsis-v"></i>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item 
                        :command="{action: 'read', reminder}"
                        v-if="!reminder.read"
                      >
                        <i class="fas fa-check mr-2"></i>标记已读
                      </el-dropdown-item>
                      <el-dropdown-item 
                        :command="{action: 'resolve', reminder}"
                        v-if="canResolve(reminder)"
                      >
                        <i class="fas fa-check-circle mr-2"></i>标记解决
                      </el-dropdown-item>
                      <el-dropdown-item 
                        :command="{action: 'dismiss', reminder}"
                      >
                        <i class="fas fa-times mr-2"></i>忽略提醒
                      </el-dropdown-item>
                      <el-dropdown-item 
                        :command="{action: 'delete', reminder}"
                        divided
                      >
                        <i class="fas fa-trash mr-2"></i>删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <div class="empty-state" v-else>
            <div class="empty-icon">
              <i class="fas fa-bell-slash"></i>
            </div>
            <div class="empty-text">
              <h3>{{ getEmptyStateTitle() }}</h3>
              <p>{{ getEmptyStateDescription() }}</p>
            </div>
          </div>
        </div>

        <!-- 面板底部 -->
        <div class="panel-footer" v-if="activeReminders.length > 0">
          <el-button @click="viewAllReminders" size="small">
            查看全部提醒
          </el-button>
          <el-button @click="cleanupReminders" type="text" size="small">
            清理已解决
          </el-button>
        </div>
      </div>
    </transition>

    <!-- 遮罩层 -->
    <div 
      class="reminder-overlay" 
      v-if="isReminderVisible"
      @click="hideReminderPanel"
    ></div>

    <!-- 浮动通知 -->
    <transition name="fade">
      <div 
        class="floating-notification" 
        v-if="showFloatingNotification && latestReminder"
        @click="handleFloatingClick"
      >
        <div class="notification-icon">
          <i :class="getReminderIcon(latestReminder.type)"></i>
        </div>
        <div class="notification-content">
          <div class="notification-title">{{ latestReminder.title }}</div>
          <div class="notification-message">{{ latestReminder.message }}</div>
        </div>
        <div class="notification-close" @click.stop="hideFloatingNotification">
          <i class="fas fa-times"></i>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useReminderStore } from '@/stores/reminder'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'

dayjs.extend(relativeTime)

export default {
  name: 'GlobalReminder',
  setup() {
    const router = useRouter()
    const reminderStore = useReminderStore()
    const userStore = useUserStore()

    // 响应式数据
    const activeTab = ref('all')
    const showFloatingNotification = ref(false)
    const latestReminder = ref(null)
    const notificationTimer = ref(null)

    // 从store中获取数据
    const {
      isReminderVisible,
      activeReminders,
      unreadReminders,
      urgentReminders,
      materialReminders,
      reminderCount,
      unreadCount,
      markAsRead,
      markAllAsRead,
      dismissReminder,
      resolveReminder,
      removeReminder,
      cleanupResolvedReminders,
      getRemindersByRole,
      hideReminderPanel,
      toggleReminderPanel
    } = reminderStore

    // 计算属性 - 根据当前标签筛选提醒
    const filteredReminders = computed(() => {
      const userRole = userStore.role
      let reminders = getRemindersByRole(userRole)

      switch (activeTab.value) {
        case 'material':
          return reminders.filter(r => 
            r.type === reminderStore.REMINDER_TYPES.MATERIAL_MISSING ||
            r.type === reminderStore.REMINDER_TYPES.MATERIAL_INCOMPLETE ||
            r.type === reminderStore.REMINDER_TYPES.MATERIAL_EXPIRED
          )
        case 'urgent':
          return reminders.filter(r => 
            r.priority === reminderStore.PRIORITY_LEVELS.URGENT ||
            r.priority === reminderStore.PRIORITY_LEVELS.HIGH
          )
        default:
          return reminders
      }
    })

    // 工具方法
    const getReminderIcon = (type) => {
      const iconMap = {
        [reminderStore.REMINDER_TYPES.MATERIAL_MISSING]: 'fas fa-file-upload text-red-500',
        [reminderStore.REMINDER_TYPES.MATERIAL_INCOMPLETE]: 'fas fa-file-excel text-orange-500',
        [reminderStore.REMINDER_TYPES.MATERIAL_EXPIRED]: 'fas fa-file-times text-red-600',
        [reminderStore.REMINDER_TYPES.DEADLINE_APPROACHING]: 'fas fa-clock text-yellow-500',
        [reminderStore.REMINDER_TYPES.REVIEW_PENDING]: 'fas fa-eye text-blue-500'
      }
      return iconMap[type] || 'fas fa-info-circle text-gray-500'
    }

    const getPriorityType = (priority) => {
      const typeMap = {
        [reminderStore.PRIORITY_LEVELS.LOW]: 'info',
        [reminderStore.PRIORITY_LEVELS.MEDIUM]: 'warning',
        [reminderStore.PRIORITY_LEVELS.HIGH]: 'danger',
        [reminderStore.PRIORITY_LEVELS.URGENT]: 'danger'
      }
      return typeMap[priority] || 'info'
    }

    const getPriorityText = (priority) => {
      const textMap = {
        [reminderStore.PRIORITY_LEVELS.LOW]: '低',
        [reminderStore.PRIORITY_LEVELS.MEDIUM]: '中',
        [reminderStore.PRIORITY_LEVELS.HIGH]: '高',
        [reminderStore.PRIORITY_LEVELS.URGENT]: '紧急'
      }
      return textMap[priority] || '普通'
    }

    const getActionIcon = (actionType) => {
      const iconMap = {
        upload: 'fas fa-upload',
        view: 'fas fa-eye',
        contact: 'fas fa-phone',
        edit: 'fas fa-edit',
        download: 'fas fa-download'
      }
      return iconMap[actionType] || 'fas fa-arrow-right'
    }

    const formatTime = (time) => {
      return dayjs(time).fromNow()
    }

    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD')
    }

    const isOverdue = (date) => {
      return dayjs().isAfter(dayjs(date))
    }

    const canResolve = (reminder) => {
      return reminder.type === reminderStore.REMINDER_TYPES.MATERIAL_MISSING ||
             reminder.type === reminderStore.REMINDER_TYPES.MATERIAL_INCOMPLETE
    }

    const getEmptyStateTitle = () => {
      switch (activeTab.value) {
        case 'material':
          return '暂无材料提醒'
        case 'urgent':
          return '暂无紧急提醒'
        default:
          return '暂无提醒'
      }
    }

    const getEmptyStateDescription = () => {
      switch (activeTab.value) {
        case 'material':
          return '所有必要材料都已完整'
        case 'urgent':
          return '当前没有紧急事项需要处理'
        default:
          return '一切都很顺利，继续保持！'
      }
    }

    // 事件处理方法
    const handleReminderClick = (reminder) => {
      if (!reminder.read) {
        markAsRead(reminder.id)
      }
    }

    const handleAction = (reminder, action) => {
      if (action.route) {
        router.push(action.route)
        hideReminderPanel()
      }
      
      // 根据操作类型执行相应逻辑
      if (action.type === 'upload') {
        ElMessage.info('正在跳转到材料上传页面...')
      } else if (action.type === 'contact') {
        ElMessage.info('正在联系相关人员...')
      }
    }

    const handleMenuAction = ({ action, reminder }) => {
      switch (action) {
        case 'read':
          markAsRead(reminder.id)
          ElMessage.success('已标记为已读')
          break
        case 'resolve':
          ElMessageBox.prompt('请输入解决说明', '标记解决', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPlaceholder: '例如：材料已上传完成'
          }).then(({ value }) => {
            resolveReminder(reminder.id, value || '已解决')
            ElMessage.success('提醒已标记为解决')
          }).catch(() => {})
          break
        case 'dismiss':
          ElMessageBox.confirm('确定要忽略这个提醒吗？', '忽略提醒', {
            type: 'warning'
          }).then(() => {
            dismissReminder(reminder.id)
            ElMessage.success('提醒已忽略')
          }).catch(() => {})
          break
        case 'delete':
          ElMessageBox.confirm('确定要删除这个提醒吗？', '删除提醒', {
            type: 'warning'
          }).then(() => {
            removeReminder(reminder.id)
            ElMessage.success('提醒已删除')
          }).catch(() => {})
          break
      }
    }

    const viewAllReminders = () => {
      // 可以跳转到专门的提醒管理页面
      ElMessage.info('提醒管理页面开发中...')
    }

    const cleanupReminders = () => {
      ElMessageBox.confirm('确定要清理7天前已解决的提醒吗？', '清理提醒', {
        type: 'info'
      }).then(() => {
        cleanupResolvedReminders(7)
        ElMessage.success('已清理历史提醒')
      }).catch(() => {})
    }

    const showFloatingNotificationFor = (reminder) => {
      latestReminder.value = reminder
      showFloatingNotification.value = true
      
      // 清除之前的计时器
      if (notificationTimer.value) {
        clearTimeout(notificationTimer.value)
      }
      
      // 5秒后自动隐藏
      notificationTimer.value = setTimeout(() => {
        hideFloatingNotification()
      }, 5000)
    }

    const hideFloatingNotification = () => {
      showFloatingNotification.value = false
      latestReminder.value = null
      if (notificationTimer.value) {
        clearTimeout(notificationTimer.value)
        notificationTimer.value = null
      }
    }

    const handleFloatingClick = () => {
      if (latestReminder.value) {
        handleReminderClick(latestReminder.value)
        toggleReminderPanel()
      }
      hideFloatingNotification()
    }

    // 监听新提醒
    watch(() => reminderStore.reminders.length, (newLength, oldLength) => {
      if (newLength > oldLength && oldLength > 0) {
        // 有新提醒时显示浮动通知
        const newestReminder = reminderStore.reminders[0]
        if (newestReminder && !newestReminder.read) {
          showFloatingNotificationFor(newestReminder)
        }
      }
    })

    // 生命周期
    onMounted(() => {
      // 初始化模拟数据（仅在开发环境）
      if (process.env.NODE_ENV === 'development') {
        reminderStore.initMockData()
      }
    })

    onUnmounted(() => {
      if (notificationTimer.value) {
        clearTimeout(notificationTimer.value)
      }
    })

    return {
      activeTab,
      showFloatingNotification,
      latestReminder,
      isReminderVisible,
      activeReminders,
      unreadReminders,
      urgentReminders,
      materialReminders,
      reminderCount,
      unreadCount,
      filteredReminders,
      getReminderIcon,
      getPriorityType,
      getPriorityText,
      getActionIcon,
      formatTime,
      formatDate,
      isOverdue,
      canResolve,
      getEmptyStateTitle,
      getEmptyStateDescription,
      handleReminderClick,
      handleAction,
      handleMenuAction,
      viewAllReminders,
      cleanupReminders,
      hideFloatingNotification,
      handleFloatingClick,
      markAllAsRead,
      hideReminderPanel,
      toggleReminderPanel
    }
  }
}
</script>

<style scoped>
.global-reminder-system {
  position: fixed;
  top: 0;
  right: 0;
  z-index: 9999;
}

/* 提醒触发器 */
.reminder-trigger {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 10000;
  cursor: pointer;
  transition: all 0.3s ease;
}

.reminder-trigger:hover {
  transform: scale(1.1);
}

.reminder-trigger.has-urgent {
  animation: urgent-pulse 2s infinite;
}

@keyframes urgent-pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

.reminder-icon {
  position: relative;
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.reminder-badge {
  position: absolute;
  top: -4px;
  right: -4px;
  background: #ef4444;
  color: white;
  border-radius: 10px;
  min-width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  border: 2px solid white;
}

/* 提醒面板 */
.reminder-panel {
  position: fixed;
  top: 0;
  right: 0;
  width: 400px;
  height: 100vh;
  background: white;
  box-shadow: -4px 0 20px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  z-index: 9999;
}

/* 面板头部 */
.panel-header {
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8fafc;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  display: flex;
  align-items: center;
}

.count-badge {
  background: #ef4444;
  color: white;
  border-radius: 12px;
  padding: 2px 8px;
  font-size: 12px;
  margin-left: 8px;
}

.header-actions {
  display: flex;
  gap: 8px;
}

/* 筛选标签 */
.panel-filters {
  padding: 0 20px;
  border-bottom: 1px solid #e5e7eb;
}

.reminder-tabs .el-tabs__header {
  margin: 0;
}

.tab-count {
  background: #e5e7eb;
  color: #6b7280;
  border-radius: 8px;
  padding: 1px 6px;
  font-size: 11px;
  margin-left: 4px;
}

/* 面板内容 */
.panel-content {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

.reminder-list {
  display: flex;
  flex-direction: column;
}

.reminder-item {
  display: flex;
  padding: 16px 20px;
  border-bottom: 1px solid #f3f4f6;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
}

.reminder-item:hover {
  background: #f8fafc;
}

.reminder-item.unread {
  background: #eff6ff;
  border-left: 4px solid #3b82f6;
}

.reminder-item.urgent {
  border-left: 4px solid #ef4444;
}

.reminder-item.high {
  border-left: 4px solid #f59e0b;
}

.reminder-item-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
}

.reminder-item-content {
  flex: 1;
  min-width: 0;
}

.reminder-item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.reminder-title {
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  line-height: 1.4;
}

.reminder-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.priority-tag {
  transform: scale(0.85);
}

.reminder-time {
  font-size: 11px;
  color: #6b7280;
}

.reminder-message {
  font-size: 13px;
  color: #4b5563;
  line-height: 1.5;
  margin: 0 0 8px 0;
}

.reminder-case-info {
  display: flex;
  gap: 12px;
  margin-bottom: 8px;
}

.case-number {
  font-size: 12px;
  color: #3b82f6;
  font-weight: 500;
}

.client-name {
  font-size: 12px;
  color: #6b7280;
}

.reminder-due-date {
  font-size: 12px;
  color: #6b7280;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.overdue-warning {
  color: #ef4444;
  font-weight: 500;
  margin-left: 4px;
}

.reminder-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.reminder-actions .el-button {
  padding: 4px 12px;
  font-size: 12px;
}

.reminder-item-menu {
  margin-left: 8px;
}

.menu-trigger {
  padding: 4px 8px;
  color: #6b7280;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #9ca3af;
  margin-bottom: 16px;
}

.empty-text h3 {
  font-size: 16px;
  color: #374151;
  margin: 0 0 8px 0;
}

.empty-text p {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

/* 面板底部 */
.panel-footer {
  padding: 16px 20px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  background: #f8fafc;
}

/* 遮罩层 */
.reminder-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 9998;
}

/* 浮动通知 */
.floating-notification {
  position: fixed;
  top: 80px;
  right: 20px;
  width: 320px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  padding: 16px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
  cursor: pointer;
  z-index: 10001;
  border-left: 4px solid #3b82f6;
}

.notification-icon {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  background: #eff6ff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-title {
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.notification-message {
  font-size: 13px;
  color: #4b5563;
  line-height: 1.4;
}

.notification-close {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.2s ease;
}

.notification-close:hover {
  background: #f3f4f6;
  color: #374151;
}

/* 过渡效果 */
.slide-left-enter-active,
.slide-left-leave-active {
  transition: transform 0.3s ease;
}

.slide-left-enter-from {
  transform: translateX(100%);
}

.slide-left-leave-to {
  transform: translateX(100%);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .reminder-panel {
    width: 100vw;
  }
  
  .floating-notification {
    width: calc(100vw - 40px);
    right: 20px;
  }
  
  .reminder-trigger {
    top: 15px;
    right: 15px;
  }
  
  .reminder-icon {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }
}

@media (max-width: 480px) {
  .panel-header,
  .panel-filters,
  .panel-footer {
    padding: 16px;
  }
  
  .reminder-item {
    padding: 12px 16px;
  }
  
  .reminder-item-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .floating-notification {
    padding: 12px;
  }
}
</style>

